<template>
	<div :class="{ expanded: expanded }" class="result-item">
		<div class="result-header" :class="{ 'no-click': props.layoutMode === 'inline' }" @click="toggleExpand">
			<div class="result-info">
				<div :class="['status-dot', validationResult.all_passed ? 'success' : 'error']"></div>
				<div class="result-details">
					<!-- 内联布局：使用网格布局确保对齐 -->
					<div v-if="props.layoutMode === 'inline'" class="inline-layout-grid">
						<div class="inline-cell inline-cell-number">
							<span class="document-number">{{ item.单据号 }}</span>
						</div>
						<div class="inline-cell inline-cell-divider">|</div>
						<div class="inline-cell inline-cell-time">
							<span class="document-time">{{ formatTime(item.推送时间) }}</span>
						</div>
						<div class="inline-cell inline-cell-divider">|</div>
						<div class="inline-cell inline-cell-status">
							<span :class="['status-text', validationResult.all_passed ? 'status-pass' : 'status-fail']">
								{{ validationResult.all_passed ? '通过' : '未通过' }}
							</span>
						</div>
						<div class="inline-cell inline-cell-divider">|</div>
						<div class="inline-cell inline-cell-info">
							<!-- 概况结果模式：显示未通过的校验项 -->
							<template v-if="props.activeTab === 'summary'">
								<template v-if="!validationResult.all_passed">
									<span class="inline-items">
										<template v-if="getFailedItems().length > 0">
											<span
												v-for="(name, index) in getFailedItems()"
												:key="index"
												class="inline-item failed"
											>
												{{ name }}
											</span>
										</template>
										<template v-else-if="Object.keys(getFailedResults()).length > 0">
											<span
												v-for="(result, name) in getFailedResults()"
												:key="name"
												class="inline-item failed"
											>
												{{ name }}
											</span>
										</template>
										<template v-else>
											<span class="inline-item failed">校验失败</span>
										</template>
									</span>
								</template>
								<template v-else>
									<span class="status-text status-pass">全部通过</span>
								</template>
							</template>
							<!-- 详细错误模式：显示错误信息 -->
							<template v-if="props.activeTab === 'detailed'">
								<template v-if="item.详细错误信息 && item.详细错误信息.length > 0">
									<span class="inline-items">
										<span
											v-for="(error, index) in item.详细错误信息"
											:key="index"
											class="inline-item error"
										>
											{{ error }}
										</span>
									</span>
								</template>
								<template v-else>
									<span class="status-text status-pass">无错误</span>
								</template>
							</template>
						</div>
						<div class="inline-cell inline-cell-divider">|</div>
					</div>
					<!-- 展开布局：保持原有布局 -->
					<div v-else class="document-info">
						<span class="document-number">{{ item.单据号 }}</span>
						<span class="document-time">{{ formatTime(item.推送时间) }}</span>
					</div>
				</div>
			</div>

			<div class="result-summary">
				<div :class="['summary-badge', validationResult.all_passed ? 'success' : 'error']">
					<template v-if="validationResult.all_passed">
						<el-icon class="summary-icon" size="16">
							<Check />
						</el-icon>
						<span>全部通过</span>
					</template>
					<template v-else>
						<el-icon class="summary-icon" size="16">
							<Close />
						</el-icon>
						<span>{{ `${getFailedCount()} 失败` }}</span>
					</template>
				</div>
				<a
					:href="jumpUrl"
					target="_blank"
					class="jump-link-wrapper"
					@click.stop
				>
					<el-icon class="jump-icon" size="18">
						<Link />
					</el-icon>
				</a>
				<div 
					class="tab-toggle-wrapper"
					@click.stop="handleTabToggle"
					:title="props.activeTab === 'summary' ? '切换到详细错误' : '切换到校验项'"
				>
					<el-icon class="tab-toggle-icon" size="18">
						<View />
					</el-icon>
				</div>
				<div v-if="props.layoutMode === 'expand'" class="expand-icon-wrapper">
					<el-icon class="expand-icon" size="18">
						<ArrowDown />
					</el-icon>
				</div>
			</div>
		</div>

		<div v-if="expanded && props.layoutMode === 'expand'" class="result-details-panel">
			<!-- 概括结果 -->
			<div v-if="props.activeTab === 'summary'" class="summary-content">
				<h4>概括结果</h4>
				<div v-if="validationResult.item_names && validationResult.item_names.length > 0" class="validation-items">
					<div
						v-for="(name, index) in validationResult.item_names"
						:key="index"
						class="validation-item"
					>
						<span class="item-name">{{ name }}</span>
						<div class="item-status">
							<div
								:class="['status-icon', validationResult.failed_items && validationResult.failed_items[index] ? 'failed' : 'success']">
								<el-icon size="14">
									<Close v-if="validationResult.failed_items && validationResult.failed_items[index]" />
									<Check v-else />
								</el-icon>
							</div>
							<span>{{
								validationResult.failed_items && validationResult.failed_items[index] ? '未通过' : '通过'
							}}</span>
						</div>
					</div>
				</div>
				<div v-else-if="validationResult.results" class="validation-items">
					<div
						v-for="(result, name) in validationResult.results"
						:key="name"
						class="validation-item"
					>
						<span class="item-name">{{ name }}</span>
						<div class="item-status">
							<div
								:class="['status-icon', Array.isArray(result) ? !result[0] : !result ? 'failed' : 'success']">
								<el-icon size="14">
									<Close v-if="Array.isArray(result) ? !result[0] : !result" />
									<Check v-else />
								</el-icon>
							</div>
							<span>{{
								Array.isArray(result) ? !result[0] ? '未通过' : '通过' : !result ? '未通过' : '通过'
							}}</span>
						</div>
					</div>
				</div>
				<div v-else class="no-data">暂无概括信息</div>
			</div>

			<!-- 详细错误 -->
			<div v-if="props.activeTab === 'detailed'" class="detailed-content">
				<h4>详细错误信息</h4>
				<div v-if="item.详细错误信息 && item.详细错误信息.length > 0" class="error-items">
					<div
						v-for="(error, index) in item.详细错误信息"
						:key="index"
						class="error-item"
					>
						<div class="error-icon">
							<el-icon size="16">
								<WarningFilled />
							</el-icon>
						</div>
						<div class="error-message">{{ error }}</div>
					</div>
				</div>
				<div v-else class="no-data">暂无详细错误信息</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { ArrowDown, Check, Close, Link, Switch, WarningFilled } from '@element-plus/icons-vue';

const props = defineProps({
	item: {
		type: Object,
		required: true
	},
	activeTab: {
		type: String,
		default: 'summary'
	},
	layoutMode: {
		type: String,
		default: 'expand'
	}
});

const emit = defineEmits(['tab-change']);

const expanded = ref(false);

const validationResult = computed(() => {
	const result = props.item.校验结果;

	// 处理复杂的字符串格式
	if (typeof result === 'string') {
		try {
			// 尝试解析JSON格式
			const parsed = JSON.parse(result);

			// 如果解析后是对象，直接返回
			if (typeof parsed === 'object' && parsed !== null) {
				return parsed;
			}

			// 如果是简单的"校验通过"字符串
			if (result === '校验通过') {
				return {
					all_passed: true,
					failed_items: []
				};
			}
		} catch {
			// 如果JSON解析失败，检查是否是"校验通过"
			if (result === '校验通过') {
				return {
					all_passed: true,
					failed_items: []
				};
			}
		}
	}

	// 处理对象格式
	if (typeof result === 'object' && result !== null) {
		// 如果all_passed是字符串，需要特殊处理
		if (typeof result.all_passed === 'string') {
			try {
				// 尝试解析all_passed字符串中的JSON
				const allPassedParsed = JSON.parse(result.all_passed);

				// 如果解析成功，使用解析后的数据
				if (allPassedParsed && allPassedParsed.results) {
					const results = allPassedParsed.results;
					const itemNames = Object.keys(results);
					const failedItems = itemNames.map(name => {
						const itemResult = results[name];
						// 检查是否是数组格式 [success, message]
						if (Array.isArray(itemResult)) {
							return !itemResult[0]; // 第一个元素是成功状态
						}
						return !itemResult; // 直接是布尔值
					});

					return {
						all_passed: !failedItems.some(failed => failed),
						item_names: itemNames,
						failed_items: failedItems
					};
				}
			} catch {
				// 如果解析失败，回退到简单处理
				return {
					all_passed: result.all_passed === '校验通过' || result.all_passed === 'true',
					failed_items: result.failed_items || []
				};
			}
		}

		return result;
	}

	// 默认返回
	return {
		all_passed: false,
		failed_items: [{ name: '未知错误' }]
	};
});

const formatTime = (timeStr: string) => {
	if (!timeStr) return '-';
	try {
		const date = new Date(timeStr);
		return date.toLocaleString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit',
			second: '2-digit'
		});
	} catch {
		return timeStr;
	}
};

const toggleExpand = () => {
	if (props.layoutMode === 'expand') {
		expanded.value = !expanded.value;
	}
};

const getFailedCount = () => {
	if (validationResult.value.failed_items) {
		if (Array.isArray(validationResult.value.failed_items)) {
			return validationResult.value.failed_items.filter((item: any) => item).length;
		}
		return validationResult.value.failed_items.length || 0;
	}
	return 0;
};

// 获取未通过的校验项名称
const getFailedItems = () => {
	if (!validationResult.value.item_names || !validationResult.value.failed_items) {
		return [];
	}
	const failedItems: string[] = [];
	validationResult.value.item_names.forEach((name: string, index: number) => {
		if (validationResult.value.failed_items && validationResult.value.failed_items[index]) {
			failedItems.push(name);
		}
	});
	return failedItems;
};

// 获取未通过的校验结果
const getFailedResults = () => {
	if (!validationResult.value.results) {
		return {};
	}
	const failed: Record<string, any> = {};
	for (const [name, result] of Object.entries(validationResult.value.results)) {
		const isFailed = Array.isArray(result) ? !result[0] : !result;
		if (isFailed) {
			failed[name] = result;
		}
	}
	return failed;
};

// 生成跳转链接
const jumpUrl = computed(() => {
	const baseUrl = 'http://cebz.chnenergy.com.cn:8082/sap/bc/ui5_ui5/ui2/ushell/shells/abap/FioriLaunchpad.html#zshquery-display?CONTROL=AL&/DEATIL/';
	const documentNumber = props.item.单据号 || '';
	return baseUrl + documentNumber;
});

// 切换标签页
const handleTabToggle = () => {
	const newTab = props.activeTab === 'summary' ? 'detailed' : 'summary';
	emit('tab-change', newTab);
};
</script>

<style scoped>
/* 结果列表 - 极简毛玻璃风格 */
.result-item {
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	background: rgba(255, 255, 255, 0.5);
	backdrop-filter: blur(10px) saturate(120%);
	-webkit-backdrop-filter: blur(10px) saturate(120%);
	border-radius: 16px;
	margin-bottom: 10px;
	overflow: hidden;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
	font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	font-feature-settings: 'kern' 1;
	text-rendering: optimizeLegibility;
}

.result-item:hover {
	background: rgba(255, 255, 255, 0.7);
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
	transform: translateY(-2px);
}

.result-item:last-child {
	margin-bottom: 0;
}

.result-header {
	padding: 16px 20px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	color: #374151;
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.result-header:not(.no-click) {
	cursor: pointer;
}

.result-header.no-click {
	cursor: default;
}

.result-header:not(.no-click):hover {
	background: rgba(255, 255, 255, 0.3);
}

.result-info {
	display: flex;
	align-items: center;
	gap: 12px;
	flex: 1;
}

.status-dot {
	width: 10px;
	height: 10px;
	border-radius: 50%;
	flex-shrink: 0;
	box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.8);
}

.status-dot.success {
	background: #48bb78;
	box-shadow: 0 0 0 2px rgba(72, 187, 120, 0.15);
}

.status-dot.error {
	background: #e14d59;
	box-shadow: 0 0 0 2px rgba(225, 77, 89, 0.15);
}

.result-details {
	flex: 1;
}

.document-info {
	display: flex;
	align-items: center;
	gap: 12px;
	flex-wrap: wrap;
}

/* 内联布局网格 */
.inline-layout-grid {
	display: grid;
	grid-template-columns: min-content 12px 140px 12px 70px 12px 1fr 12px;
	align-items: center;
	gap: 0;
	width: 100%;
}

.inline-cell {
	display: flex;
	align-items: center;
	justify-content: center;
}

.inline-cell-number {
	justify-content: flex-start;
	padding-right: 8px;
	text-align: left;
	min-width: 0;
	white-space: nowrap;
}

.inline-cell-time {
	justify-content: center;
	padding: 0 8px;
	text-align: center;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.inline-cell-status {
	justify-content: center;
	padding: 0 8px;
	text-align: center;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.inline-cell-info {
	justify-content: flex-start;
	padding-left: 8px;
	display: flex;
	flex-wrap: wrap;
	align-items: center;
	text-align: left;
	min-width: 0;
	word-break: break-word;
	overflow-wrap: break-word;
}

.inline-cell-divider {
	color: #d1d5db;
	font-weight: 300;
	justify-content: center;
	width: 12px;
	flex-shrink: 0;
	text-align: center;
}

.status-text {
	font-size: 0.875rem;
	font-weight: 500;
	letter-spacing: -0.01em;
}

.status-text.status-pass {
	color: #38a169;
}

.status-text.status-fail {
	color: #c53030;
}

.document-number {
	font-weight: 600;
	color: #4a5568;
	font-size: 1rem;
	letter-spacing: -0.02em;
	line-height: 1.4;
	font-feature-settings: 'kern' 1;
}

.document-time {
	color: #8b95a7;
	font-size: 0.875rem;
	font-weight: 400;
	letter-spacing: -0.01em;
	line-height: 1.5;
	font-feature-settings: 'kern' 1;
}

/* 内联信息样式 */
.inline-info-wrapper {
	display: contents;
}

.inline-info {
	display: flex;
	align-items: center;
	gap: 8px;
	color: #6b7c96;
	font-size: 0.875rem;
	margin-left: 8px;
}

.inline-divider {
	color: #d1d5db;
	margin: 0 4px;
}

.inline-label {
	font-weight: 500;
	color: #8b95a7;
	font-size: 0.8125rem;
}

.inline-items {
	display: flex;
	align-items: center;
	gap: 8px;
	flex-wrap: wrap;
}

.inline-item {
	padding: 4px 10px;
	border-radius: 12px;
	font-size: 0.8125rem;
	font-weight: 500;
	line-height: 1.4;
}

.inline-item.failed {
	background: rgba(225, 77, 89, 0.1);
	color: #c53030;
	border: 1px solid rgba(225, 77, 89, 0.2);
}

.inline-item.error {
	background: rgba(225, 77, 89, 0.1);
	color: #c53030;
	border: 1px solid rgba(225, 77, 89, 0.2);
}

.result-summary {
	display: flex;
	align-items: center;
	gap: 10px;
}

.jump-link-wrapper {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 32px;
	height: 32px;
	border-radius: 8px;
	background: rgba(0, 0, 0, 0.03);
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	cursor: pointer;
	text-decoration: none;
	margin-right: 8px;
}

.jump-link-wrapper:hover {
	background: rgba(0, 0, 0, 0.06);
}

.jump-icon {
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	color: #8b95a7;
	font-size: 18px;
}

.jump-link-wrapper:hover .jump-icon {
	color: #6b7c96;
	transform: scale(1.1);
}

.tab-toggle-wrapper {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 32px;
	height: 32px;
	border-radius: 8px;
	background: rgba(0, 0, 0, 0.03);
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	cursor: pointer;
	margin-right: 8px;
}

.tab-toggle-wrapper:hover {
	background: rgba(0, 0, 0, 0.06);
}

.tab-toggle-icon {
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	color: #8b95a7;
	font-size: 18px;
}

.tab-toggle-wrapper:hover .tab-toggle-icon {
	color: #6b7c96;
	transform: scale(1.1);
}

.summary-badge {
	padding: 8px 16px;
	border-radius: 12px;
	font-size: 0.8125rem;
	font-weight: 500;
	min-width: 100px;
	text-align: center;
	display: inline-flex;
	align-items: center;
	justify-content: center;
	gap: 6px;
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	letter-spacing: -0.01em;
	line-height: 1.4;
	font-feature-settings: 'kern' 1;
}

.summary-badge .summary-icon {
	font-size: 15px;
	line-height: 1;
}

.summary-badge.success {
	background: rgba(72, 187, 120, 0.12);
	color: #38a169;
	border: 1px solid rgba(72, 187, 120, 0.18);
}

.summary-badge.error {
	background: rgba(225, 77, 89, 0.12);
	color: #c53030;
	border: 1px solid rgba(225, 77, 89, 0.18);
}

.expand-icon-wrapper {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 32px;
	height: 32px;
	border-radius: 8px;
	background: rgba(0, 0, 0, 0.03);
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	cursor: pointer;
}

.expand-icon-wrapper:hover {
	background: rgba(0, 0, 0, 0.06);
}

.expand-icon {
	transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	color: #8b95a7;
	font-size: 16px;
}

.result-item.expanded .expand-icon {
	transform: rotate(180deg);
}

/* 详情面板 - 极简毛玻璃风格 */
.result-details-panel {
	background: rgba(255, 255, 255, 0.45);
	backdrop-filter: blur(12px) saturate(130%);
	-webkit-backdrop-filter: blur(12px) saturate(130%);
	padding: 20px;
}

.summary-content h4,
.detailed-content h4 {
	margin: 0 0 16px 0;
	color: #4a5568;
	font-size: 1.0625rem;
	font-weight: 600;
	letter-spacing: -0.02em;
	line-height: 1.4;
	font-feature-settings: 'kern' 1;
}

.validation-items,
.error-items {
	display: flex;
	flex-direction: column;
	gap: 0;
}

.validation-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 12px 0;
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.validation-item:hover {
	background: rgba(107, 124, 150, 0.05);
	margin: 0 -20px;
	padding-left: 20px;
	padding-right: 20px;
	border-radius: 10px;
}

.item-name {
	color: #4a5568;
	font-weight: 500;
	font-size: 0.9375rem;
	letter-spacing: -0.01em;
	line-height: 1.5;
	font-feature-settings: 'kern' 1;
}

.item-status {
	display: flex;
	align-items: center;
	gap: 8px;
}

.status-icon {
	width: 22px;
	height: 22px;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 12px;
	color: white;
	font-weight: 600;
	flex-shrink: 0;
}

.status-icon.success {
	background: #48bb78;
	box-shadow: 0 2px 8px rgba(72, 187, 120, 0.2);
}

.status-icon.failed {
	background: #e14d59;
	box-shadow: 0 2px 8px rgba(225, 77, 89, 0.2);
}

.error-item {
	display: flex;
	align-items: flex-start;
	gap: 10px;
	padding: 12px 0;
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.error-item:hover {
	background: rgba(225, 77, 89, 0.05);
	margin: 0 -20px;
	padding-left: 20px;
	padding-right: 20px;
	border-radius: 10px;
}

.error-icon {
	width: 24px;
	height: 24px;
	background: rgba(225, 77, 89, 0.85);
	color: #ffffff;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: 600;
	flex-shrink: 0;
	font-size: 13px;
	box-shadow: 0 2px 8px rgba(225, 77, 89, 0.2);
}

.error-message {
	color: #4a5568;
	line-height: 1.6;
	flex: 1;
	font-size: 0.9375rem;
	letter-spacing: -0.01em;
	font-feature-settings: 'kern' 1;
}

.no-data {
	color: #8b95a7;
	font-style: italic;
	text-align: center;
	padding: 30px 20px;
	font-size: 0.9375rem;
	letter-spacing: -0.01em;
	line-height: 1.6;
	font-feature-settings: 'kern' 1;
}

@media (max-width: 768px) {
	.result-header {
		flex-direction: column;
		align-items: flex-start;
		gap: 12px;
		padding: 16px;
	}

	.result-details-panel {
		padding: 16px;
	}

	.result-summary {
		width: 100%;
		justify-content: space-between;
	}
}
</style>

